#include "history.h"
#include "ui_history.h"

History::History(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::History)
{
    ui->setupUi(this);

    setupRealtimeDataDemo(ui->customPlot);//初始化图表
    ui->customPlot->replot();

    ui->checkBoxN->setChecked(true);
    ui->checkBoxP->setChecked(true);

    connect(ui->pushButtonSelectStart,SIGNAL(clicked()),this,SLOT(StartSlot()));
    connect(ui->pushButtonSelectStop,SIGNAL(clicked()),this,SLOT(StopSlot()));


    //    long timestamp = 1666482615;
    // 使用QDateTime::fromSecsSinceEpoch将时间戳转换为QDateTime对象
    // 将QDateTime对象转换为字符串格式的日期和时间
    //       QString dateTimeStr = QDateTime::fromMSecsSinceEpoch(timestamp).toString("yyyy-MM-dd HH:mm:ss");

    //       // 输出转换后的日期时间字符串
    //       qDebug() << "转换后的日期时间：" << dateTimeStr;
}

History::~History()
{
    delete ui;
}

void History::setupRealtimeDataDemo(QCustomPlot *customPlot)
{
    //#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0)
    //QMessageBox::critical(this, "", "You're using Qt < 4.7, the realtime data demo needs functions that are available with Qt 4.7 to work properly");
    //#endif
    //demoName = "Real Time Data Demo";

    // include this section to fully disable antialiasing for higher performance:
    /*
  customPlot->setNotAntialiasedElements(QCP::aeAll);
  QFont font;
  font.setStyleStrategy(QFont::NoAntialias);
  customPlot->xAxis->setTickLabelFont(font);
  customPlot->yAxis->setTickLabelFont(font);
  customPlot->legend->setFont(font);
  */
    customPlot->addGraph(); // blue line
    customPlot->graph(0)->setPen(QPen(Qt::blue));
    customPlot->graph(0)->setName("氮");
    //customPlot->graph(0)->setBrush(QBrush(QColor(240, 255, 200)));
    //customPlot->graph(0)->setAntialiasedFill(false);
    customPlot->addGraph(); // red line
    customPlot->graph(1)->setPen(QPen(Qt::red));
    customPlot->graph(1)->setName("磷");
    //customPlot->graph(0)->setChannelFillGraph(customPlot->graph(1));


    customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime);
    customPlot->xAxis->setDateTimeFormat("MM-dd hh:mm:ss");
    customPlot->xAxis->setAutoTickStep(false);
    customPlot->xAxis->setTickStep(2);
    customPlot->axisRect()->setupFullAxesBox();

    // make left and bottom axes transfer their ranges to right and top axes:
    //connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange)));
    //connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange)));

    // setup a timer that repeatedly calls MainWindow::realtimeDataSlot:
   // connect(&dataTimer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot()));
    QObject::connect(GlobalVal::mqtt, SIGNAL(historySignal(QByteArray)),
                     this, SLOT(realtimeDataSlot(QByteArray)));
    dataTimer.start(1000); // Interval 0 means to refresh as fast as possible
    customPlot->legend->setVisible(true);
}



void History::realtimeDataSlot( const QByteArray& payload)
{
    qDebug()<<"payload="<<payload;
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(payload, &parseError);

    if (parseError.error != QJsonParseError::NoError) {
        qDebug() << "解析JSON失败：" << parseError.errorString();
        return;
    }

    if (!doc.isObject()) {
        qDebug() << "JSON不是对象类型";
        return;
    }


    //key的单位是秒
    //double key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0;
    //qsrand(QTime::currentTime().msec() + QTime::currentTime().second() * 10000);
    //使用随机数产生两条曲线
    QJsonObject obj=doc.object();
    QJsonArray data_arry=obj.value("data").toArray();
    double latest_time=0;//记录最新时间戳
    for(const QJsonValue& value:data_arry)
    {
        if(!value.isObject())continue;
        QJsonObject dataObj=value.toObject();
        int key0=dataObj.value("key").toInt();
        double val=dataObj.value("value").toString().toDouble();
        qint64 timestamp=dataObj.value("timestamp").toVariant().toLongLong();
        latest_time = std::max(latest_time, (double)timestamp);
        if(key0==301)
        {
            qDebug()<<"N val:"<<val;
            if (ui->checkBoxN->isChecked())
                ui->customPlot->graph(0)->addData(timestamp, val);//添加数据1到曲线1
        }
        else if(key0==302)
        {
              qDebug()<<"P val:"<<val;
            if (ui->checkBoxP->isChecked())
                ui->customPlot->graph(1)->addData(timestamp, val);//添加数据2到曲线2
        }
    }
//    double value0 = qrand() % 100;
//    double value1 = qrand() % 80;
//    if (ui->checkBoxN->isChecked())
//        ui->customPlot->graph(0)->addData(key, value0);//添加数据1到曲线1
//    if (ui->checkBoxP->isChecked())
//        ui->customPlot->graph(1)->addData(key, value1);//添加数据2到曲线2
    //删除8秒之前的数据。这里的8要和下面设置横坐标宽度的8配合起来
    //才能起到想要的效果，可以调整这两个值，观察显示的效果。
    ui->customPlot->graph(0)->removeDataBefore(latest_time-8);
    ui->customPlot->graph(1)->removeDataBefore(latest_time-8);

    //自动设定graph(1)曲线y轴的范围，如果不设定，有可能看不到图像
    //也可以用ui->customPlot->yAxis->setRange(up,low)手动设定y轴范围
//    ui->customPlot->graph(0)->rescaleValueAxis();
//    ui->customPlot->graph(1)->rescaleValueAxis(true);
        ui->customPlot->yAxis->setRange(90,20);

    //这里的8，是指横坐标时间宽度为8秒，如果想要横坐标显示更多的时间
    //就把8调整为比较大到值，比如要显示60秒，那就改成60。
    //这时removeDataBefore(key-8)中的8也要改成60，否则曲线显示不完整。
   if(!isPaused){
    ui->customPlot->xAxis->setRange(latest_time+0.25, 8, Qt::AlignRight);//设定x轴的范围
    ui->customPlot->replot();
   }
}

void History::StartSlot()
{
    ui->pushButtonSelectStart->setEnabled(false);
    ui->pushButtonSelectStop->setEnabled(true);
    isPaused=false;
    //发送开始JSON数据包
    QDateTime datetime=ui->dateTimeEdit->dateTime();
    qint64 timestamp=datetime.toMSecsSinceEpoch()/1000;
    QJsonObject obj;
    obj["type"]=4;
    obj["time"]=static_cast<qint64>(timestamp);//确保是整数
    obj["status"]=1;
    QJsonDocument doc(obj);
    QByteArray payload=doc.toJson(QJsonDocument::Compact);
    QMQTT::Message msg;
    msg.setTopic("/app/control/down");
    msg.setPayload(payload);
   // qDebug()<<"topic="<<msg.topic();
    qDebug()<<"start="<<msg.payload();
    GlobalVal::mqtt->publish(msg);
}

void History::StopSlot()
{
    ui->pushButtonSelectStart->setEnabled(true);
    ui->pushButtonSelectStop->setEnabled(false);
    isPaused=true;
    QDateTime datetime=ui->dateTimeEdit->dateTime();
    qint64 timestamp=datetime.toMSecsSinceEpoch()/1000;
    //发送结束数据包
    QJsonObject obj;
    obj["type"]=4;
    obj["status"]=0;
    obj["time"]=static_cast<qint64>(timestamp);//确保是整数
    QJsonDocument doc(obj);
    QByteArray payload=doc.toJson(QJsonDocument::Compact);
    QMQTT::Message msg;
    msg.setTopic("/app/control/down");
    msg.setPayload(payload);
   // qDebug()<<"topic="<<msg.topic();
    qDebug()<<"stop="<<msg.payload();
    GlobalVal::mqtt->publish(msg);

}
